<script setup lang="ts">

import {Input} from "~/components/ui/input";
import {FormField, FormControl, FormDescription, FormItem, FormLabel, FormMessage} from "~/components/ui/form";
import {useForm} from "vee-validate";
import useAuthStore from "~/stores/authStore";
import {Toaster, useToast} from "~/components/ui/toast";


const { toast } = useToast()
const  authStore = useAuthStore()

type TypeForm = {
  name: string,
  label: string,
  placeholder: string,
  type: string,
}

const forms = ref<TypeForm[]>([
  {
    name: 'first_name',
    label: 'Имя',
    placeholder: 'Иван',
    type: 'text'
  },
  {
    name: 'last_name',
    label: 'Фамилия',
    placeholder: 'Иванов',
    type: 'text'
  },
  {
    name: 'email',
    label: 'Email',
    placeholder: 'email@example.com',
    type: 'text'
  },
  {
    name: 'password',
    label: 'Пароль',
    placeholder: 'Пароль',
    type: 'password'
  },
])


const { handleSubmit, setErrors } = useForm()

const submitForm = handleSubmit( async (values) => {
  const {data, error, response} = await client.register(values)
  if (error) {
    if  (response.status  === 400){
      setErrors(error)
    }
  }
  if (data) {
    authStore.login(data.token, data.isAdmin)
    navigateTo('/cabinet')
  }
})

</script>

<template>
  <Toaster/>
  <main class="container flex-grow flex-shrink-0 grid grid-cols-12 justify-center items-center">
    <div class="w-full p-10 border-accent border lg:col-start-4 lg:col-end-10 md:col-start-3 md:col-end-11 sm:col-start-2 sm:col-end-12 col-start-1 col-end-13 rounded-2xl flex flex-col justify-center items-center">
      <h3 class="text-2xl">Регистрация</h3>
      <form @submit.prevent="submitForm" class="w-full">
        <FormField v-for="form in forms" :name="form.name" :key="form.name" v-slot="{ componentField }">
          <FormItem v-auto-animate>
            <FormLabel>{{ form.label }}</FormLabel>
            <FormControl>
              <Input :placeholder="form.placeholder" v-bind="componentField" :type="form.type"/>
            </FormControl>
            <FormDescription />
            <FormMessage />
          </FormItem>
        </FormField>
        <Button type="submit" class="w-full text-md mt-5">Зарегестрироватся</Button>
        <NuxtLink to="/login"><Button type="button" class="w-full text-md mt-5" variant="secondary">Авторизация</Button></NuxtLink>
      </form>
    </div>
  </main>
</template>

<style scoped>

</style>